﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RonYee.Models;
using System.Data.Linq.SqlClient;
using RonYee.Service;
using System.IO;

namespace RonYee.Controllers
{
    public class BookController : Controller
    {
        RongeDb db = new RongeDb();
        //
        // GET: /Book/

        #region  //对Books图书表进行管理

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Index()
        {

            RonYee.Models.MvcPage Model = new MvcPage();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Book> datesource = GetDataSource();//要分页的数据源
            Model.BookList = datesource.Where(r => r.BookId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.BookList = datesource.Where(r => r.BookId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<Book> GetDataSource()
        {
            var book = from b in db.Books
                       where b.BookCount > 0
                       orderby b.BookName ascending
                       select b;
            List<Book> model = new List<Book>();
            foreach (var item in book)
            {
                model.Add(item);
            }
            return model;
        }

        public ActionResult PageIndex(RonYee.Models.MvcPage Model)
        {

            //分页数据源。自己写逻辑获取。


            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Book> datesource = GetDataSource();//要分页的数据源
            Model.BookList = datesource.Where(r => r.BookId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("Index", Model);
            }
            //return View(Model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Search()
        {
            string isbn = Request.Form["s_isbn"];
            string name = Request.Form["s_name"];
            //11
            if (isbn != "" && name != "")
            {
                var book = from b in db.Books
                           where b.ISBN.Contains(isbn) && b.BookName.Contains(name)
                           orderby b.ISBN ascending
                           select b;
                return View(book);
            }
            //10
            else if (isbn != "" && name == "" )
            {
                var book = from b in db.Books
                           where b.ISBN.Contains(isbn)
                           orderby b.ISBN ascending
                           select b;
                return View(book);
            }
            //01
            else if (isbn == "" && name != "")
            {
                var book = from b in db.Books
                           where b.BookName.Contains(name)
                           orderby b.ISBN ascending
                           select b;
                return View(book);
            }
            else
            {
                return RedirectToAction("Index");
            }

        }


        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Details(int id)
        {
            Book book = db.Books.Find(id);

            string type1 = (from b in db.Books
                         where b.BookId == id
                         select b.BookType1).FirstOrDefault();
            string img = (from b in db.Books
                          where b.BookId == id
                          select b.BookImage).FirstOrDefault();
            ViewBag.type1 = type1;
            ViewBag.image = img;


            return View(book);
        }
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Edit(int id)
        {
            Book book = db.Books.Find(id);
            ViewBag.Isbn = book.ISBN;
            return View(book);
        }

        [HttpPost]
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult SaveEdit()
        {
            string filename = "DefaultCover.jpg";
            string path = "DefaultValue";
            string isbn = Request.Form["ISBN"];
            decimal percent = 1;
            if (Request.Form["setpercent"] != "") 
            {
                decimal a1= Convert.ToDecimal(Request.Form["setpercent"]);
                if (a1 > 0 && a1 < 1) 
                {
                    percent = a1;
                }
            }
            string fileOldName = "";
            string extension = "";
            string fileNewName = "";

            foreach (string bookCover in Request.Files)
            {
                if (!RonYee.Service.HasFiles.HasFile(Request.Files[bookCover]))
                    continue;

                string createPath = AppDomain.CurrentDomain.BaseDirectory + @"FilesPool\BookCover";
                path = HasFolders.HasFolder(createPath);

                //获得文件扩展名
                fileOldName = Path.GetFileName(Request.Files[bookCover].FileName);
                extension = System.IO.Path.GetExtension(fileOldName);//扩展名 “.xxx”
                Stream fileStream = Request.Files[bookCover].InputStream;
                //文件重命名
                fileNewName = RandomNumberTo.RandomNumberToName() + extension;
                Request.Files[bookCover].SaveAs(Path.Combine(path, fileNewName));
                
            }
            int id = Convert.ToInt32(Request.Form["BookId"]);
            var book = db.Books.Find(id);


            book.Publisher = Request.Form["Publisher"];
            book.PublishNum = Request.Form["PublishNum"];
            book.Author = Request.Form["Author"];
            book.OriginalPrice = Convert.ToDecimal(Request.Form["OriginalPrice"]);
            book.CurrentPrice = book.OriginalPrice * percent;
            book.BookType1 = Request.Form["BookType1"];
            book.DelImgUrl = Path.Combine(path, fileNewName);
            book.BookImage = path + filename;

            UpdateModel(book);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Delete(int id)
        {
            Book book = db.Books.Find(id);
            return View(book);
        }

        [HttpPost]
        [Authorize(Roles = "Admin,Editer")]
        public RedirectToRouteResult Delete(int id, FormCollection collection)
        {
            var book = db.Books.Find(id);
            db.Books.Remove(book);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        [Authorize(Roles = "Admin")]
        public ActionResult SetPercent() 
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult DoSetPercent()
        {
            if (Request.Form["myPercent"] != "" && Request.Form["myPercent"] != null)
            {
                decimal percent = Convert.ToDecimal(Request.Form["myPercent"]);
                if (percent > 0 && percent < 1)
                {
                    var book = from b in db.Books select b;
                    foreach (Book item in book)
                    {
                        UpdateInBooks(item.ISBN, percent);
                    }
                    return RedirectToAction("Index");
                }
                else 
                {
                    return View();
                }
            }
            else 
            {
                return View();
            }
        }

        public void UpdateInBooks(string isbn, decimal percent)
        {
            try
            {
                int id = GetBooksInfo.GetBooksID(isbn);
                var b = db.Books.Find(id);
                if (b != null)
                {
                    b.CurrentPrice = b.OriginalPrice * percent;
                    UpdateModel<Book>(b);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message;
            }

        }

        #endregion

    }
}
